
import router from '../router'
import store from '../store'
import axios from 'axios'
// 配置API接口地址
const root = process.env.VUE_APP_API_ROOT;
const timeOut = process.env.VUE_APP_TIME_OUT;

/**
 * 请求拦截
 */
// axios.interceptors.request.use(config => {
  // let Authorization = 'Bearer '+localStorage.getItem("FL_TOKEN");
  // if (!config.headers) {
  //   config.headers = {}
  // }
  // if(Authorization){
  //   config.headers.Authorization = Authorization;
  // }
  // return config
// });
/**
 * 响应拦截
 */
axios.interceptors.response.use(function (response) {
  // 接口状态码处理
  handleResCode(response);
  return response;
}, (err) => {
  console.log(err)
  // 错误码提示信息
  errCodeMessage(err);
  return Promise.reject(err);
});
/** 方法 **/
// 自定义判断元素类型JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

// 参数过滤函数
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/**
 * 响应拦截错误码处理
 * @param err 错误信息
 */
function errCodeMessage(err) {
  if (!err.response) {
    err.message = '网络异常';
  }
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '请求错误';
        break;
      case 401:
        err.message = '未授权，请登录';
        break;
      case 403:
        err.message = '拒绝访问';
        break;
      case 404:
        err.message = `404 请求地址出错`;
        break;
      case 408:
        err.message = '请求超时';
        break;
      case 500:
        err.message = '网络异常';
        break;
      case 501:
        err.message = '网络异常';
        break;
      case 502:
        err.message = '网络异常';
        break;
      case 503:
        err.message = '网络异常';
        break;
      case 504:
        err.message = '网络异常';
        break;
      case 505:
        err.message = '网络异常';
        break;
      default: err.message = '网络异常';
    }
  }
}

/**
 * 响应拦截接口状态码处理
 * @param res 接口返回信息
 */
function handleResCode(res) {

  switch (res.data.code) {
    case 200: // 成功
      break;
    case 1002: // 成功
      break;
    case 1001:
      localStorage.removeItem('FL_TOKEN');
      // Dialog.alert({
      //   message:"登录过期"
      // }).then(()=>{
      //   let fromInfo = {
      //     name:router.history.current.name,
      //     query:router.history.current.query,
      //     params:router.history.current.params
      //   }
      //   fromInfo.params.isAuth = true;
      //   localStorage.setItem('fromInfo',JSON.stringify(fromInfo))
      //   router.replace({name:'Login'})
      // })
      break;
    default: // 错误
      if (res.config.wapLoading === 1) {
        res.config.wapLoading = 2;
      }
      break;
  }
  // 若接口状态码成功 加载状态修改为成功
  if (res.config.wapLoading !== 0) {
    if (res.config.wapLoading === 1) {
      res.config.wapLoading = 0;
    }
  }

}
/*
  接口处理函数
*/
function apiAxios(method, url, params, loading) {
  // 设置部分网页处于加载中状态;
  if (params) {
    params.api_token=localStorage.getItem("FL_TOKEN")
    params = filterNull(params)
  }
  return axios({
    method: method === 'file' ? 'POST' : method,
    url: url,
    data: method === 'file' || method === 'POST' ? params : null,
    params: method === 'GET' ? params : null,
    baseURL: root,
    timeout: timeOut,
    // withCredentials: true,
    transformRequest: [function (data) {
      if (method === 'file') {
        return data
      } else {
        let ret = '';
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }
    }],
    headers: {
      "Content-Type": method === 'file' ? "multipart/form-data" : "application/x-www-form-urlencoded",
    }
  })
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params, loading = {loading: 0}) {
    return apiAxios('GET', url, params, loading)
  },
  post: function (url, params, loading = {loading: 0}) {
    return apiAxios('POST', url, params, loading)
  },
  file: function (url, params,loading = {loading: 0}) {
    return apiAxios('file', url, params, loading)
  },
}
